const Utils = {
  storage_set (name, value, expired = 600) {
    if (!name) return null
    if (typeof value === 'undefined') throw new Error('The value must be filled in, may be null!')
    const storage = window.localStorage
    const date = new Date()
    const key = `STORAGE_${String(name).toLocaleUpperCase()}`
    if (value === null) {
      // if (storage.hasOwnProperty(key)) {
      if (Object.prototype.hasOwnProperty.call(storage, 'key')) {
        storage.removeItem(key)
      }
    } else {
      storage.setItem(key, JSON.stringify({
        value,
        expired: expired > 0 ? date.getTime() + expired * 1000 : 0
      }))
    }
    return false
  },
  storage_get (name, defaultValue) {
    if (!name) return null
    const storage = window.localStorage
    const key = `STORAGE_${String(name).toLocaleUpperCase()}`
    const date = new Date()
    let item = storage.getItem(key)
    if (item) {
      item = JSON.parse(item)
      // console.log(item.expired - date.getTime());
      if (item.expired > 0 && item.expired - date.getTime() < 0) {
        storage.removeItem(key)
      } else {
        return item.value
      }
    }
    return defaultValue || null
  }
}

export default Utils
